package com.yunang.officialweb.common;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;

/**
 * @author zhou
 */
@Data
@ApiModel(value = "全局统一返回结果")
public class R<T> {
    @ApiModelProperty(value = "返回码")
    private Integer code;

    @ApiModelProperty(value = "返回消息")
    private String message;

    @ApiModelProperty(value = "返回数据")
    private T data;

    public R(){

    }

    public static <T> R<T> build(T data){           //前面的<T>是声明这是一个泛型方法，虽然R<T>就是泛型类，但是这里又static
        R<T> R = new R<T>();
        if (data != null) {
            R.setData(data);
        }
        return R;
    }

    public static <T> R<T> build(T data, RCodeEnum rCodeEnum){
        R<T> R = build(data);
        R.setCode(rCodeEnum.getCode());
        R.setMessage(rCodeEnum.getMessage());
        return R;
    }

    public static <T> R<T> build(Integer code, String message){
        R<T> R =build(null);
        R.setCode(code);
        R.setMessage(message);
        return R;
    }

    //操作成功
    public static <T> R<T> ok(){
        return R.ok(null);
    }

    public static <T> R<T> ok(T data){
        R<T> R = build(data);
        return build(data, RCodeEnum.SUCCESS);
    }

    //操作失败
    public static <T> R<T> fail(){
        return R.fail(null);
    }

    public static <T> R<T> fail(T data){
        R<T> R = build(data);
        return build(data, RCodeEnum.FAIL);
    }
}
